import { useHttp } from './useHttp'

export function getRequestUrl(service: string, type = 'select', app: any) {
  const config = useRuntimeConfig()
  const baseApp = app || config.public.baseApp
  const baseApi = config.public.baseApi
  return `${baseApi}/${baseApp}/${type}/${service}`
}

export function onLogin(data) {
  const req = [{
    serviceName: 'srvuser_login',
    data: [{ user_no: data.user_no, pwd: data.pwd, terminal_type: 'PC' }],
  }]
  const url = getRequestUrl('srvuser_login', 'operate', 'sso')
  return useHttp.post(url, req)
}

export async function getScanConfig(callbackurl) {
  const request = {}
  request.serviceName = 'srvwx_web_scan_cfg_select'
  request.colNames = ['*']
  request.condition = [{ colName: 'callbackurl', value: callbackurl }]
  const url = getRequestUrl('srvwx_web_scan_cfg_select', 'select', 'wx')
  const rsp = await useHttp.post(url, request)
  const data = rsp.data[0]
  // if(data.bx_auth_ticket){
  //   sessionStorage.setItem("bx_auth_ticket", data.bx_auth_ticket)
  // }
  // var obj = new WxLogin({
  //   self_redirect: false,
  //   id: "login_container",
  //   appid: data.appid,
  //   scope: "snsapi_login",
  //   redirect_uri: data.callbackurl,
  //   state: data.state,
  //   style: "black",
  //   href: window.location.origin + "/main/css/loginqrcode.css"
  // });
}
// // 用户扫码授权处理
export function scanLogin(code, state) {
  // const service = 'srvwx_web_scan_auth'
  const service = 'srvwx_web_scan_auth_login'
  // const service = 'srvwx_web_scan_auth'
  const data = {
    code,
    state,
  }
  const request = {}
  request.serviceName = service
  request.data = []
  request.data.push(data)
  const bxRequest = []
  bxRequest.push(request)
  const url = getRequestUrl(service, 'operate', 'wx')
  return useHttp.post(url, bxRequest)
}

export async function getWxLoginConfig() {
  const url = getRequestUrl('srvwx_web_scan_cfg_select', 'select', 'wx')
  const req = {
    serviceName: 'srvwx_web_scan_cfg_select',
    colNames: ['*'],
    condition: [
      { colName: 'callbackurl', value: 'https://saas.100xsys.cn/main/login.html' },
    ],
  }
  const res = await useHttp.post(url, req)
  if (res.state === 'SUCCESS') {
    const data = res.data[0]
    // {
    //   "bx_auth_ticket": "xabxdzkj-64bbc4ff-ab06-45aa-a9b7-2a0f516f58b0",
    //   "appid": "wxd016be5549cfc967",
    //   "callbackurl": "https%3A%2F%2Fsaas.100xsys.cn%2Fmain%2Flogin.html",
    //   "state": "537e716745a043f2ba93ce993d56ca92"
    // }
    if (data.bx_auth_ticket) {
      if (import.meta.client) {
        localStorage.setItem('bx_auth_ticket', data.bx_auth_ticket)
      }
      return data
    }
  }
  else if (res.resultMessage) {
    if (res.resultMessage?.includes('code been used')) {
    }
    else {
      ElMessage.error(res.resultMessage)
    }
  }
  return res
}
